import { Tooltip, cssVar, udp } from '@cscec/udp-ui';
import styles from './index.less';
import React from 'react';
import { useMenu } from '../../service';

const { accessToken } = udp.getUser();
const moduleCode = udp.getQueryValue('moduleCode') || '1720259054527471617';

export function Card(props: any) {
  const {
    menuIcon, funcName, funcDesc, menuUrl, menuName, routeName, menuCode, env,
  } = props;

  const menuClick = ({ menuUrl, routeName, menuName }: any) => async () => {
    if (env?.session !== 'render') {
      return;
    }

    // 打开的时候记录下 点击过的菜单
    await useMenu({
      moduleCode,
      menuCode
    });

    udp.open(menuUrl, { microAppName: routeName || 'portal', AppTitle: menuName });
  };

  const getMenuIcon = (menuIcon: string) => {
    if (menuIcon?.indexOf('http') === 0) {
      return menuIcon;
    }
    if (menuIcon?.indexOf('/minio-upload') === 0) {
      return udp.getHttpUrl(`/minio/${menuIcon}`)
    }
    const url = `/udp-file/doc/file/preview?fileId=${menuIcon}&User-Token=${accessToken}&t=${new Date().getTime()}`
    return udp.getHttpUrl(url);
  }

  const getIcon = (menuIcon: string, menuName: string) => {
    if (!menuIcon && menuName) {
      return <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', fontSize: 28, width: 56, height: 56, color: '#fff', background: cssVar.primaryColor, borderRadius: 4 }}>{menuName[0]}</div>;
    }
    return <img style={{ width: 56, height: 56 }} src={getMenuIcon(menuIcon)} />;
  };

  return (
    <div className={styles.card} onClick={menuClick({ menuUrl, routeName, menuName: menuName || funcName })}>
      <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        {getIcon(menuIcon, menuName)}
        <div className={`nowrap ${styles.menuName}`} style={{ marginTop: 10 }}>
          <span style={{ wordBreak: 'break-all' }}>
            {menuName.length > 12 ? <Tooltip title={menuName}>{menuName}</Tooltip> : menuName}
          </span>
        </div>
      </div>
      <div className={styles.right}>
        <Tooltip title={funcName} overflow>
          <div className={styles.title}>{funcName}</div>
        </Tooltip>
        <Tooltip title={funcDesc} overflow>
          <div className={styles.desc}>{funcDesc}</div>
        </Tooltip>
      </div>
    </div>
  );
}
